import { GlobalStore } from '@/stores';
import { Notify } from 'quasar';
const WSS_URL = 'ws://124.222.229.185:8000';
let Socket: any = '';
let setIntervalWesocketPush: any = null;
const globalStore = GlobalStore();
// 建立连接
export function createSocket() {
  if (!Socket) {
    console.log('建立websocket连接');
    Socket = new WebSocket(WSS_URL + `?Authorization=${globalStore.token}`);
    Socket.onopen = onopenWS;
    Socket.onmessage = onmessageWS;
    Socket.onerror = onerrorWS;
    Socket.onclose = oncloseWS;
  } else {
    console.log('websocket已连接');
  }
}
// 打开WS之后发送心跳
export function onopenWS() {
  sendPing(); //发送心跳
}
// 连接失败重连
export function onerrorWS() {
  clearInterval(setIntervalWesocketPush);
  Socket.close();
  createSocket(); //重连
}
// WS数据接收统一处理
export function onmessageWS(e: any) {
  window.dispatchEvent(
    new CustomEvent('onmessageWS', {
      detail: {
        data: e,
      },
    })
  );
}
/**发送数据
 1. @param eventType
 */
export function sendWSPush(obj: any) {
  console.log('1111111111111111-----------', Socket, obj);
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close();
    createSocket(); //重连
    Notify.create({
      color: 'white',
      textColor: 'negative',
      icon: 'cancel',
      position: 'top',
      message: '连接已断开',
    });
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(obj));
    console.log('发送--1', Socket.readyState);
  } else if (Socket.readyState === 0) {
    console.log('发送--0', Socket.readyState);
    setTimeout(() => {
      Socket.send(JSON.stringify(obj));
    }, 1000);
  }
}
/**关闭WS */
export function oncloseWS() {
  clearInterval(setIntervalWesocketPush);
  Notify.create({
    color: 'white',
    textColor: 'negative',
    icon: 'cancel',
    position: 'top',
    message: 'webscoket连接已断开',
  });
}
/**发送心跳 */
export function sendPing() {
  Socket.send(
    JSON.stringify({
      action: 'back/ping',
    })
  );
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(
      JSON.stringify({
        action: 'back/ping',
      })
    );
    console.log('发送心跳');
  }, 5000);
}
